// MIT License (MIT)
// 
// Copyright (c) 2014 K Ercan Turkarslan
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// 

using System;
using System.Diagnostics;
using System.Linq;
using System.Xml.Linq;
using CodeGen;
using CollectionsLibrary;

namespace MiosGenerator
{
    public class StateVariable : MiosCollectionItem
    {
        public Boolean SendEvents { get; set; }
        public Boolean AllowRepeats { get; set; }
        public String DefaultValue { get; set; }
        public string ShortCode { get; private set; }
        public UpnpDataType DataType { get; private set; }
        internal VariableCondition Condition { get; private set; }
        public Action GetMethod { get; set; }
        public Action SetMethod { get; set; }

        #region Readonly Property GetMethodName : String;
        private String _getMethodName;
        private String GetMethodName
        {
            get {
                return _getMethodName ??
                       (_getMethodName = (GetMethod == null) ? String.Format("Get{0}", Name) : GetMethod.Name);
            }
        }
        #endregion

        #region Generate Method

        #region Get Property
        private void GeneratePropertyGet(CodeBlock cb)
        {
            cb.PrivateMember(DataType.Nullable, Name);
            cb.NewLine();

            cb.Insert(String.Format("public {0} {1}", DataType.CSharp, Name));
            cb.Begin_Block();
            cb.Begin_Get();

            cb.Insert(String.Format("return _m{0} ?? {1}();", Name, GetMethodName));

            cb.End_Get();
            cb.End_Block();
            cb.NewLine();
        }

        #endregion

        #region GenerateGetMethod
        private void GenerateGetMethod(CodeBlock cb)
        {
            if (GetMethod == null)
            {
                cb.Comment(
                    "WARNING: Service Description File does not contain any Get Action with a",
                    "argument related to this State Variable.",
                    "",
                    "This may be due to a typo while defining the Get Action or state variable.",
                    "This may also be intentional. Code generator assumes this was a mistake and",
                    "generates this Get Action."
                    );
            }

            cb.Action_Begin(GetMethodName, "", DataType.CSharp);

                cb.Insert(
                    String.Format("_m{0} = FromLuup{1}(Engine.Luup_VariableGet(base.DeviceId, base.ServiceId, \"{0}\"));",
                        Name,
                        DataType.CSharp));
                cb.NewLine();
                cb.Insert(String.Format("return _m{0}{1};", Name, DataType.IsString ? "" : ".Value"));

            cb.Action_End(GetMethodName);
        }
        #endregion

        #region GenerateSetMethod
        private void GenerateSetMethod(CodeBlock cb)
        {
            if (SetMethod == null)
                return;

            var argumentName = SetMethod.FirstArgument.Name;
            var camelParamName = SetMethod.FirstArgument.CamelCaseName;

            cb.Action_Begin(SetMethod.Name, String.Format("{0} {1}", DataType.CSharp, camelParamName), "String");

                if (DataType.IsString)
                {
                    cb.CheckNullOrEmptyStringParameter(camelParamName);
                }

                if (Condition != null)
                {
                    Condition.Generate(cb, DataType, camelParamName);
                }

                cb.Insert(String.Format("return Engine.Luup_CallAction(base.DeviceId, base.ServiceId, \"{0}\",", SetMethod.Name));
                cb.InsertIndented(String.Format("String.Format(\"{0}={{0}}\", ToLuup(_m{1} = {2})));", argumentName, Name, camelParamName));

            cb.Action_End(SetMethod.Name);
        }
        #endregion

        internal void Generate(CodeBlock cb)
        {
            Debug.Assert(Name != null, "actionName != null");
            Debug.Assert(cb != null, "cb != null");
            Debug.Assert(DataType.CSharp != null, "DataType.CSharp != null");

            cb.Region_Begin(String.Format("{0} : {1};", Name, DataType.CSharp));

                if (!FromDescription)
                {
                    cb.Comment(
                        "WARNING: This state variable was not defined in the Service Description file.",
                        "However it was referenced by one or more Actions as their related state variable.",
                        "Or it was returned by Vera in USER_DATA xml.",
                        "This may be due to a typo in RelatedStateVariable definition or missing State Variable.");
                }

                GeneratePropertyGet(cb);

                GenerateSetMethod(cb);
                GenerateGetMethod(cb);

            cb.Region_End();
        }

        #endregion

        #region Constructors
        internal StateVariable(XNode xNode)
            : base(xNode.GetValue("name"))
        {
            var sendEvents = xNode.Attributes("sendEvents");

            if (sendEvents == String.Empty)
            {
                sendEvents = xNode.GetValue("sendEventsAttribute");
            }

            SendEvents = (sendEvents == "yes");
            AllowRepeats = (xNode.Attributes("allowRepeats") == "yes");         
            DefaultValue = xNode.GetValue("defaultValue");
            ShortCode = xNode.GetValue("shortCode");

            DataType = new UpnpDataType(xNode.GetValue("dataType"));

            if (xNode.GetChildren("allowedValueList").Any())
            {
                Condition = new AllowedValueList(xNode);
            }

            if (xNode.GetChildren("allowedValueRange").Any())
            {
                Condition = new AllowedValueRange(xNode);
            }

            GetMethod = null;
            SetMethod = null;
        }

        internal StateVariable(String name, String dataType)
            : base(name)
        {
            FromDescription = false;

            DataType = new UpnpDataType(dataType);

            GetMethod = null;
            SetMethod = null;
        }
        #endregion        
    }
}